package cn.edu.web;

import cn.edu.dao.BookDao;
import cn.edu.pojo.Book;
import cn.edu.service.BookService;
import cn.edu.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

public class BookServlet extends BaseServlet {
    BookService bookService = new BookServiceImpl();
    protected void addBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sn = req.getParameter("sn");
        String name = req.getParameter("name");
        String author = req.getParameter("author");
        String price = req.getParameter("price");
        String publish = req.getParameter("publish");
        Book book = new Book(sn,name,new BigDecimal(Double.parseDouble(price)),author,publish);
        int i = bookService.addBook(book);
        resp.sendRedirect(req.getContextPath()+"/bookServlet?action=allBook");
    }
        protected void updateBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sn = req.getParameter("id");
        String bname = req.getParameter("name");
        String author = req.getParameter("author");
        String publish = req.getParameter("publish");
        String price = req.getParameter("price");
        Book book = new Book(sn,bname,new BigDecimal(Double.parseDouble(price)),author,publish);
        bookService.updateBook(book);
        resp.sendRedirect(req.getContextPath()+"/bookServlet?action=allBook");
    }
        protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sn = req.getParameter("sn");
        Book book = bookService.getBookBySn(sn);
        req.setAttribute("bookObj",book);
        req.getRequestDispatcher("/book_edit.jsp").forward(req,resp);
    }

    protected void deleteBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sn = req.getParameter("sn");
        int i = bookService.deleteBook(sn);
        if (i==1){
            resp.sendRedirect(req.getContextPath()+"/bookServlet?action=allBook");
        }else {
            //可能已被收藏表引用无法删除
        }
    }
        protected void allBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Book> books = bookService.allBook();
        req.setAttribute("books",books);
        req.getRequestDispatcher("/bookTop.jsp").forward(req,resp);
    }
}
